package com.varian.auth.authentication.handler;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.varian.tool.Func;
import com.varian.tool.contant.ResultConstant;
import com.varian.tool.result.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;

/**
 * @author ben
 * @since 2024/6/28
 */
public class VarianAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        R<Object> result = R.result(ResultConstant.FAIL);
        if (exception instanceof OAuth2AuthenticationException) {
            OAuth2Error error = ((OAuth2AuthenticationException) exception).getError();
            result.setMessage(error.getDescription());
        }
        response.setStatus(result.getStatus());
        JakartaServletUtil.write(response, Func.jackson2JsonStr(result), MediaType.APPLICATION_JSON_VALUE);
    }
}
